package com.tingyuge.base.thread.queue;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaodao
 * date: 2020/4/6
 */
public class DelayedQueueTest {

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<MovieTicket> delayQueue = new DelayQueue();
        MovieTicket movieTicket1 = new MovieTicket("电影票1",5,TimeUnit.SECONDS);
        MovieTicket movieTicket2 = new MovieTicket("电影票2",15,TimeUnit.SECONDS);
        MovieTicket movieTicket3 = new MovieTicket("电影票3",10,TimeUnit.SECONDS);
        delayQueue.put(movieTicket1);
        delayQueue.put(movieTicket2);
        delayQueue.put(movieTicket3);

        System.out.println("begin time:" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        for (int i = 0; i < 3; i++) {
            MovieTicket take = delayQueue.take();
            System.out.format("name:{%s}, time:{%s}\n",take.getName(), LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }

    }
}


class MovieTicket implements Delayed {
    //名字
    private String name;
    //延时时间
    private long time;

    public MovieTicket(String name, long time,TimeUnit unit) {
        this.name = name;
        this.time = System.currentTimeMillis() + (time > 0? unit.toMillis(time): 0);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return "MovieTicket{" +
                "name='" + name + '\'' +
                ", time=" + time +
                '}';
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return time - System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed o) {
       /* MovieTicket item = (MovieTicket) o;
        long diff = this.time - item.time;
        if (diff <= 0) {// 改成>=会造成问题
            return -1;
        }else {
            return 1;
        }*/
       return 0;
    }
}